<?php
namespace App\Http\Controllers;
/**
 *
 * 线路订单控制器
 *
 * @author maqu
 *
 */

use App\Models\TourOrder;
use App\Models\TourOrderRefund;
use App\Models\TourStatistics;
use App\Models\User;
use App\Services\OrderPingppService;
use App\Services\TourOrderService;
use App\Services\TourRefundService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;

class TourOrdersController extends BaseController {

    /**创建订单
     * @param TourOrderService $tourOrderService
     * @return mixed
     */
    public function createTourOrderSingle(TourOrderService $tourOrderService){
        //线路id
        $tour_id = Input::get('tour_id');

        //线路日程id
        $schedule_id = Input::get('schedule_id',0);

        //用户id
        $user_id = Input::get('user_id');

        if(!$user_id || !$tour_id){
            return $this->args_invalid();
        }

        if(!$schedule_id){
            return $this->failure('请选择出行日程');
        }

        //出行人成年人人数
        $amount_a = Input::get('amount_a',0);
        //出行人儿童人数
        $amount_c = Input::get('amount_c',0);

        //出行人id字符串  用逗号','分割
        $traveler_ids = Input::get('traveler_ids');

        /*选择的附加项目
         * json 格式
          [
            {
                "tservice_id": 1,//附加项目id
                "tservice_amount": "1"//附加项目数量
            },
            {
                "tservice_id": 2,
                "tservice_amount": "3"
            }
          ]
        */
        $options = Input::get('options');

        $linkman_name = Input::get('linkman_name');
        $linkman_phone = Input::get('linkman_phone');
        $postscript = Input::get('postscript','');

        if(!$linkman_name || !$linkman_phone){
            return $this->failure('请填写联系人姓名和电话');
        }

        $linkman = new \stdClass;
        $linkman->linkman_name = $linkman_name;
        $linkman->linkman_phone = $linkman_phone;
        $linkman->postscript = $postscript;

        if($amount_a == 0 && $amount_c == 0){
            return $this->failure('成人儿童的数量总和必须大于0');
        }
        $traveler_arr = explode(',',$traveler_ids);
        $count_traveler = count($traveler_arr);
        if($count_traveler == 0){
            return $this->failure('请选择出行人');
        }

        if($count_traveler > ($amount_a+$amount_c)){
            return $this->failure('人数超出限制');
        }elseif($count_traveler < ($amount_a+$amount_c)){
            return $this->failure('还有剩余的出行人位置未选择，请删减数量或者添加出行人');
        }

        //获取出行人数据并判断出行人选择的是否正确
        $travelersData = $tourOrderService->findTravelers($user_id,$traveler_arr);
        if(!$travelersData['result']){
            return $this->failure($travelersData['msg']);
        }

        //出行人信息
        $travelers = $travelersData['data'];
        $temp_a = $amount_a;
        $temp_c = $amount_c;
        //判断出行人选择的成人和儿童数量是否一一对应
        foreach($travelers as $item){
            if($item->is_child){
                $temp_c --;
            }else{
                $temp_a --;
            }
        }
        if($temp_a != 0 || $temp_c != 0){
            return $this->failure('出行人成年人与儿童的数量与实际选择的出行人不符');
        }

        $createData = $tourOrderService->createSingleOrder($user_id,$tour_id,$schedule_id,$amount_a,$amount_c,$options,$travelers,$linkman);

        if(!$createData['result']){
            return $this->failure($createData['msg']);
        }

        $orderInfo = $createData['data'];
        $data = new \stdClass;
        $data->order_id = $orderInfo->order_id;
        $data->order_status = $orderInfo->status;
        $data->order_amount = $orderInfo->order_amount;
        $data->payment_id = $orderInfo->payment_id;
        $data->payment_name = $orderInfo->payment_name;
        $data->payment_code = $orderInfo->payment_code;

        return $this->success($data);

    }

    /**创建团购和订单
     * @param TourOrderService $tourOrderService
     * @return mixed
     */
    public function createTourOrderGroup(TourOrderService $tourOrderService){
        //线路id
        $tour_id = Input::get('tour_id');

        //线路日程id
        $schedule_id = Input::get('schedule_id',0);

        //用户id
        $user_id = Input::get('user_id');

        if(!$user_id || !$tour_id){
            return $this->args_invalid();
        }

        if(!$schedule_id){
            return $this->failure('请选择出行日程');
        }

        //组团人数
        $copy_peoples = Input::get('copy_peoples',0);
        if(!$copy_peoples){
            return $this->failure('请选择组团人数');
        }

        //团类型0-公开 1-私有
        $tuan_type = Input::get('tuan_type',0);

        //私有团组团密码
        $tuan_password = Input::get('tuan_password','');

        if($tuan_type == TOUR_TUAN_TYPE_PRIVATE){
            if(empty($tuan_password)){
                return $this->failure('请填写组团密码');
            }
        }else{
            $tuan_password = '';
        }

        //组团宣言
        $slogan = Input::get('slogan','');

        //购买的份数
        $copies = Input::get('copies',0);
        if(!$copies){
            return $this->failure('团购至少购买一份');
        }

        if($copies > $copy_peoples){
            return $this->failure('团购购买的份数不可超过组团份数数量');
        }

        //出行人id字符串  用逗号','分割
        $traveler_ids = Input::get('traveler_ids');

        //联系人信息与留言
        $linkman_name = Input::get('linkman_name');
        $linkman_phone = Input::get('linkman_phone');
        $postscript = Input::get('postscript','');

        if(!$linkman_name || !$linkman_phone){
            return $this->failure('请填写联系人姓名和电话');
        }

        $linkman = new \stdClass;
        $linkman->linkman_name = $linkman_name;
        $linkman->linkman_phone = $linkman_phone;
        $linkman->postscript = $postscript;

        $traveler_arr = explode(',',$traveler_ids);
        $count_traveler = count($traveler_arr);
        if($count_traveler == 0){
            return $this->failure('请选择出行人');
        }

        $createData = $tourOrderService->createGroupOrder($user_id,$tour_id,$schedule_id,$copy_peoples,$tuan_type,$tuan_password,$copies,$slogan,$traveler_arr,$linkman);

        if(!$createData['result']){
            return $this->failure($createData['msg']);
        }

        $orderInfo = $createData['data'];
        $data = new \stdClass;
        $data->order_id = $orderInfo->order_id;
        $data->order_status = $orderInfo->status;
        $data->order_amount = $orderInfo->order_amount;
        $data->payment_id = $orderInfo->payment_id;
        $data->payment_name = $orderInfo->payment_name;
        $data->payment_code = $orderInfo->payment_code;

        return $this->success($data);

    }

    /**参加团购并创建订单
     * @param TourOrderService $tourOrderService
     * @return mixed
     */
    public function joinTourOrderGroup(TourOrderService $tourOrderService){
        $tuan_id = Input::get('tuan_id');

        //用户id
        $user_id = Input::get('user_id');

        if(!$user_id || !$tuan_id){
            return $this->args_invalid();
        }

        //如果是私有团，则需要参团密码
        $tuan_password = Input::get('tuan_password','');

        //购买的份数
        $copies = Input::get('copies',0);
        if(!$copies){
            return $this->failure('团购至少购买一份');
        }

        //出行人id字符串  用逗号','分割
        $traveler_ids = Input::get('traveler_ids');

        //联系人信息与留言
        $linkman_name = Input::get('linkman_name');
        $linkman_phone = Input::get('linkman_phone');
        $postscript = Input::get('postscript','');

        if(!$linkman_name || !$linkman_phone){
            return $this->failure('请填写联系人姓名和电话');
        }

        $linkman = new \stdClass;
        $linkman->linkman_name = $linkman_name;
        $linkman->linkman_phone = $linkman_phone;
        $linkman->postscript = $postscript;

        $traveler_arr = explode(',',$traveler_ids);
        $count_traveler = count($traveler_arr);
        if($count_traveler == 0){
            return $this->failure('请选择出行人');
        }

        $createData = $tourOrderService->joinGroupOrder($user_id,$tuan_id,$tuan_password,$copies,$traveler_arr,$linkman);

        if(!$createData['result']){
            return $this->failure($createData['msg']);
        }

        $orderInfo = $createData['data'];
        $data = new \stdClass;
        $data->order_id = $orderInfo->order_id;
        $data->order_status = $orderInfo->status;
        $data->order_amount = $orderInfo->order_amount;
        $data->payment_id = $orderInfo->payment_id;
        $data->payment_name = $orderInfo->payment_name;
        $data->payment_code = $orderInfo->payment_code;

        return $this->success($data);

    }

    /**获取支付方式para
     * @param $user_id
     * @param $order_id
     * @param TourOrderService $tourOrderService
     * @param OrderPingppService $orderPingppService
     * @return mixed
     */
    public function gotoPayTourOrder($user_id,$order_id,TourOrderService $tourOrderService,OrderPingppService $orderPingppService){
        //支付类型
        $pay_channel = Input::get('pay_channel','');

        //是否需要全部的返回数据
        $needs_full = Input::get('needs_full',0);

        if(!$user_id){
            return $this->failure('请先登录');
        }

        if (!$order_id)
        {
            return $this->failure('未找到订单');
        }

        if (!$pay_channel)
        {
            return $this->failure('请选择支付方式');
        }

        //获取订单信息
        $tourOrderInfoData = $tourOrderService->getOrderInfo($user_id,$order_id);

        if(!$tourOrderInfoData['result']){
            return $this->failure($tourOrderInfoData['msg']);
        }

        $tourOrderInfo = $tourOrderInfoData['data'];

        if($tourOrderInfo->buyer_id != $user_id ){
            return $this->failure('无权操作该订单');
        }

        if($tourOrderInfo->extension == TOUR_ORDER_EXTENSION_NORMAL){
            //如果库存不足，则支付失败
            if($tourOrderInfo->tourOrderTour->quantity > $tourOrderInfo->tourOrderTour->tourSchedule->stock){
                return $this->failure('该日程剩余出行人数不足，请重新下单');
            }
        }

        if($tourOrderInfo->extension == TOUR_ORDER_EXTENSION_GROUPBUY){
            if($tourOrderInfo->tourOrderTour->tourSchedule->stock == 0){
                return $this->failure('该日程出行人数已满，无法支付下单');
            }
        }

        if($tourOrderInfo->status != TOUR_ORDER_PENDING){
            return $this->failure('该订单不可支付');
        }

        $checkChennelData = $orderPingppService->checkChennel($pay_channel);
        if(!$checkChennelData['result']){
            return $this->failure($checkChennelData['msg']);
        }

        $channel = $checkChennelData['data'];

        //获取支付para
        $payparaData = $orderPingppService->getPayPara($user_id,$order_id,$tourOrderInfo->seller_name,$tourOrderInfo->order_sn,$tourOrderInfo->order_amount,$pay_channel,$needs_full);
        if(!$payparaData['result']){
            return $this->failure($payparaData['msg']);
        }

        //更新订单支付方式
        $updateData = $tourOrderService->updateOrderPaymentType($channel,$tourOrderInfo,true);
        if(!$updateData['result']){
            return $this->failure($updateData['msg']);
        }

        return $this->success($payparaData['data']);

    }

    /**个人订单列表
     * @param $user_id
     * @param TourOrderService $tourOrderService
     * @return mixed
     */
    public function lists($user_id,TourOrderService $tourOrderService){

        if(!$user_id){
            return $this->failure('请先登录');
        }

        $order_state = Input::get('order_state','all');//  团状态 全部 all/待支付 pending/待出行 accepted/待评价 waite_evaluate
        $firstrow = Input::get('firstrow',0);
        $pagesize = Input::get('pagesize',10);

        $tourOrderListData = $tourOrderService->getTourOrderList($user_id,$order_state,$firstrow,$pagesize);

        if(!$tourOrderListData['result']){
            return $this->failure($tourOrderListData['msg']);
        }

        $tourOrderList = $tourOrderListData['data'];

        return $this->success($tourOrderList);
    }

    /**个人订单列表
     * @param $user_id
     * @param $id
     * @param TourOrderService $tourOrderService
     * @return mixed
     */
    public function detail($user_id,$id,TourOrderService $tourOrderService){

        if(!$user_id){
            return $this->failure('请先登录');
        }

        if(!$id){
            return $this->args_invalid();
        }

        $tourOrderDetailData = $tourOrderService->getTourOrderDetail($user_id,$id);

        if(!$tourOrderDetailData['result']){
            return $this->failure($tourOrderDetailData['msg']);
        }

        $tourOrder = $tourOrderDetailData['data'];

        return $this->success($tourOrder);
    }

    /**
     * 买家取消订单
     * @param $user_id
     * @param int $id
     * @param TourOrderService $tourOrderService
     * @return mixed
     */
    public function cancel($user_id,$id=0,TourOrderService $tourOrderService){
        if(!$user_id){
            return $this->failure('请先登录');
        }

        if(!$id){
            return $this->args_invalid();
        }

        $cancelResult = $tourOrderService->cancelTourOrder($user_id,$id,true);
        if(!$cancelResult['result']){
            return $this->failure($cancelResult['msg']);
        }

        return $this->success();

    }

    /**
     * 删除订单
     * @param $user_id
     * @param int $id
     * @param TourOrderService $tourOrderService
     * @return mixed
     */
    function delete($user_id,$id=0,TourOrderService $tourOrderService)
    {
        if(!$user_id){
            return $this->failure('请先登录');
        }

        if(!$id){
            return $this->args_invalid();
        }

        $deleteResult = $tourOrderService->deleteTourOrder($user_id,$id,true);
        if(!$deleteResult['result']){
            return $this->failure($deleteResult['msg']);
        }

        return $this->success();
    }

    //评价
    public function evaluate($user_id,$id,TourOrderService $tourOrderService){
        if(!$user_id){
            return $this->failure('请先登录');
        }
        if(!$id){
            return $this->args_invalid();
        }

        $evaluation = Input::get("evaluation");//星级
        $comment = Input::get("comment");//评论

        $evaluation_images_arr = Input::get('evaluation_images');

        $anonymous = Input::get("anonymous",0);//是否匿名
        if(!$evaluation){
            return $this->failure('请填写星級');
        }

        if(!$comment){
            return $this->failure('请填写评论');
        }

        //处理上传的图片
        $evaluation_images = [];
        if(count($evaluation_images_arr)>0){
            foreach($evaluation_images_arr as $i => $image){
                $temps = explode(',',$image);
                $img = base64_decode($temps[1]);
                $filepath = '/data/evaluation/' . local_date_ymd(gmtime()) .'/' ;
                $filename = $filepath . 'evaluation_'.$i.'_'.gmtime() . '.jpg';

                Storage::disk()->put($filename,$img);

                $evaluation_images[]=$filename;
            }
        }

        $evaluationResult = $tourOrderService->evaluationTourOrder($user_id,$id,$evaluation,$comment,$evaluation_images,$anonymous,true);

        if(!$evaluationResult['result']){
            return $this->failure($evaluationResult['msg']);
        }

        return $this->success();

    }

    //投诉
    public function complain($user_id,$id, TourOrderService $tourOrderService){
        if(!$user_id){
            return $this->failure('请先登录');
        }
        if(!$id){
            return $this->args_invalid();
        }

        $link_name = Input::get('link_name');
        $link_phone = Input::get('link_phone');

        if(!$link_name){
            return $this->failure('请填写联系人');
        }

        if(!$link_phone){
            return $this->failure('请填写联系号码');
        }

        if(!is_mobile($link_phone)){
            return $this->failure('请填写正确的手机号码');
        }

        $comment = Input::get("comment");//描述

        $complain_images_arr = Input::get('complain_images');
        //处理上传的图片
        $complain_images = [];
        if(count($complain_images_arr)>0){
            foreach($complain_images_arr as $i => $image){
                $temps = explode(',',$image);
                $img = base64_decode($temps[1]);
                $filepath = '/data/tour_complain/' . local_date_ymd(gmtime()) .'/' ;
                $filename = $filepath . 'complain_'.$i.'_'.gmtime() .'.jpg';
                Storage::disk()->put($filename,$img);
                $complain_images[]=$filename;
            }
        }
        $tourOrderService->complainTourOrder($user_id,$id,$link_name,$link_phone,$comment,$complain_images,'tour',true);
    }

    /**
     * 买家-退款申请
     * @param $user_id：用户id
     * @param $id：订单id
     * @param TourOrderService $tourOrderService
     * @return mixed
     */
    public function getApplyRefund($user_id,$id,TourOrderService $tourOrderService){
        if(!$user_id){
            return $this->failure('请先登录');
        }

        if (!$id)
        {
            return $this->failure('未找到订单');
        }

        //获取订单信息
        $tourOrderInfoData = $tourOrderService->getOrderInfo($user_id,$id);

        if(!$tourOrderInfoData['result']){
            return $this->failure($tourOrderInfoData['msg']);
        }
        $tourOrderInfo = $tourOrderInfoData['data'];

        if($tourOrderInfo->buyer_id != $user_id ){
            return $this->failure('无权操作该订单');
        }

        if($tourOrderInfo->status == TOUR_ORDER_PENDING){
            return $this->failure('该订单尚未支付');
        }elseif($tourOrderInfo->status != TOUR_ORDER_ACCEPTED && $tourOrderInfo->status != TOUR_ORDER_SUBMITTED ){
            return $this->failure('该旅行订单已出行或者已经申请退款，不可重复申请退款');
        }
        if($tourOrderInfo->tourOrderRefund){
            if($tourOrderInfo->tourOrderRefund->refund_status == TOUR_REFUND_PENDING || $tourOrderInfo->tourOrderRefund->refund_status == TOUR_REFUND_REFUNDING){
                return $this->failure('已经申请退款,请勿重复申请，可询问客服查询进度');
            }
        }
        //配置项
        $configs = app('maqu.config')->getAllConfigs();
        $tour_refund_singlebuy = $configs[CONFIG_CODE_tour_refund_singlebuy];
        $tour_refund_groupbuy_before = $configs[CONFIG_CODE_tour_refund_groupbuy_before];
        $tour_refund_groupbuy_after = $configs[CONFIG_CODE_tour_refund_groupbuy_after];
        $tour_refund_deadline = $configs[CONFIG_CODE_tour_refund_deadline];

        $rest_time = $tourOrderInfo->tourOrderTour->open_date-gmtime();
        $rest_date = $rest_time/86400;
        if($rest_date < $tour_refund_deadline){
            return $this->failure('距离出行日期还有'.$rest_time.'天已不可退款');
        }

        $tour_refund_percent = 0;
        switch($tourOrderInfo->extension){
            case 'normal':
                $tour_refund_percent = $tour_refund_singlebuy;
                $tuan_status ='';
                break;
            case 'groupbuy':
                if($tourOrderInfo->tourTuan->state == TUAN_STATE_WAITE){
                    $tour_refund_percent = $tour_refund_groupbuy_before;
                    $tuan_status = TUAN_STATE_WAITE;
                }elseif($tourOrderInfo->tourTuan->state == TUAN_STATE_SUCCESS){
                    $tour_refund_percent = $tour_refund_groupbuy_after;
                    $tuan_status = TUAN_STATE_WAITE;
                }
                break;
            default:;
        }

        $refund_fee = $tourOrderInfo->order_amount * (100 - $tour_refund_percent)/100;
        $reasons = [
            '订单信息有误/拍错',
            '个人原因无法出行',
            '其他'
        ];
        $data = [
            'tuan_status'=> $tuan_status,
            'order_amount'=> $tourOrderInfo->order_amount,
            'refund_fee' => $refund_fee,
            'charg_percent' => $tour_refund_percent,
            'reasons' =>$reasons
        ];

        return $this->success($data);

    }

    /**
     * 买家-退款申请数据提交
     * @param $user_id：用户id
     * @param $id：订单id
     * @param TourRefundService $tourRefundService
     * @return mixed
     */
    public function postApplyRefund($user_id,$id,TourRefundService $tourRefundService){
        if(!$user_id){
            return $this->failure('请先登录');
        }

        if (!$id)
        {
            return $this->failure('未找到订单');
        }
        
        $reason = Input::get('reason','');
        $tuan_status = Input::get('tuan_status','');


        //获取订单信息
        $applyRefundData = $tourRefundService->applyRefundTourOrder($user_id,$id,$reason,$tuan_status,true);
        if(!$applyRefundData['result']){
            return $this->failure($applyRefundData['msg']);
        }

        return $this->success(null,'您的申请已经提交成功，请关注审核退款进度');

    }

    /**
     *
     * 取消退款
     *
     * @param $user_id
     * @param $order_id
     * @return mixed
     * @throws Exception
     */
    public function postCancelRefund($user_id,$order_id){


        if(!$order_id){
            return $this->failure('参数不对');
        }

        $user_name = DB::table('member')->where('user_id',$user_id)->pluck('user_name')[0];
        $tourOrderService = new TourOrderService();
        $orderInfo = $tourOrderService->getOrderInfo($user_id,$order_id);

        //判断订单是否存在
        if(!$orderInfo){
            return $this->failure('订单不存在');
        }

        //订单状态不是退款中，不可以取消申请
        if($orderInfo['data']->status != TOUR_ORDER_REFUNDING){
            return $this->failure('该订单不可取消退款');
        }
//        dd($orderInfo['data']->tourOrderRefund->refund_id);
        if(!$orderInfo['data']->tourOrderRefund->refund_id){
            return $this->failure('该订单不可取消退款');
        }

        DB::beginTransaction();

        try{
            DB::table('tour_order_refund')
                ->where('order_id',$order_id)
                ->update([
                    'refund_status' => TOUR_ORDER_ACCEPTED,//待出行
                ]);

            //添加记录
            $refundService = new TourRefundService();
            $remark = "取消退款申请";
            $refundService->addOrderRefundLog($orderInfo['data']->tourOrderRefund->refund_id,$user_name,'用户申请退款','用户取消退款',$remark);

            DB::table('tour_order')
                ->where('order_id',$order_id)
                ->update([
                    'status' => TOUR_ORDER_ACCEPTED,//待出行
                ]);

            /* 操作记录 */
            $order_log = [
                'order_id'  => $order_id,
                'operator'  => $user_id,
                'order_status' => '退款中',
                'changed_status' =>'待出行' ,
                'remark'    => '用户取消退款',
                'log_time'  => gmtime(),
            ];

            DB::table('tour_order_log')->insert($order_log);

            DB::commit();

            return $this->success(null);

        }catch(Exception $e){
            DB::rollback();
            throw $e;
        }

    }
}